package com.ChainBizPro.system.controller;

import com.ChainBizPro.system.annotation.AuthCheck;
import com.ChainBizPro.system.common.BaseResponse;
import com.ChainBizPro.system.common.DeleteRequest;
import com.ChainBizPro.system.common.ErrorCode;
import com.ChainBizPro.system.common.ResultUtils;
import com.ChainBizPro.system.constant.UserConstant;
import com.ChainBizPro.system.exception.BusinessException;
import com.ChainBizPro.system.exception.ThrowUtils;
import com.ChainBizPro.system.model.domain.Orderaftersales;
import com.ChainBizPro.system.model.domain.User;
import com.ChainBizPro.system.model.dto.Order.OrderaftersalesQueryRequest;
import com.ChainBizPro.system.model.dto.orderaftersale.OrderaftersalesAddRequest;
import com.ChainBizPro.system.model.dto.orderaftersale.OrderaftersalesCheckRequest;
import com.ChainBizPro.system.model.dto.orderaftersale.OrderaftersalesUpdateRequest;
import com.ChainBizPro.system.model.vo.OrderaftersalesVO;
import com.ChainBizPro.system.service.OrderaftersalesService;
import com.ChainBizPro.system.service.PurchaseOrdersService;
import com.ChainBizPro.system.service.SuppliersService;
import com.ChainBizPro.system.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * 订单售后接口
 *
 * @author liusijia
 */
@RestController
@RequestMapping("/orderaftersale")
@Api(tags = "订单售后接口")
@Slf4j
public class OrderaftersalesController {

    @Resource
    private PurchaseOrdersService purchaseOrdersService;

    @Resource
    private SuppliersService suppliersService;

    @Resource
    private UserService userService;

    @Resource
    private OrderaftersalesService orderaftersalesService;

    // region 增删改查

    /**
     * 创建订单售后
     *
     * @param orderaftersalesAdd
     * @param request
     * @return SupplierId
     */
    @PostMapping("/add")
    @ApiOperation(value = "创建订单售后")
    public BaseResponse<Integer> addOrderaftersales(@RequestBody OrderaftersalesAddRequest orderaftersalesAdd, HttpServletRequest request) {
        if (orderaftersalesAdd == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数为空");
        }
        User loginUser = userService.getLoginUser(request);
        Orderaftersales orderaftersales = new Orderaftersales();
        BeanUtils.copyProperties(orderaftersalesAdd, orderaftersales);
        orderaftersales.setUserId(loginUser.getId());
        orderaftersales.setRequestTime(new Date());
        boolean result = orderaftersalesService.save(orderaftersales);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "创建订单售后失败");
        return ResultUtils.success(orderaftersales.getAfterSalesId());
    }

    /**
     * 删除订单售后
     *
     * @param deleteRequest
     * @return
     */
    @PostMapping("/delete")
    @ApiOperation(value = "删除订单售后")
    public BaseResponse<Boolean> deleteOrderaftersales(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数为空");
        }
        QueryWrapper<Orderaftersales> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("afterSalesId", deleteRequest.getId());
        boolean result = orderaftersalesService.removeById(deleteRequest.getId());
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "删除失败");
        return ResultUtils.success(result);
    }

    /**
     * 更新订单售后
     *
     * @param orderaftersalesUpdate
     * @param request
     * @return
     */
    @PostMapping("/update")
    @ApiOperation(value = "更新订单售后(仅用户和管理员)")
    public BaseResponse<Boolean> updateOrderaftersales(@RequestBody OrderaftersalesUpdateRequest orderaftersalesUpdate, HttpServletRequest request) {
        if (orderaftersalesUpdate == null || orderaftersalesUpdate.getAfterSalesId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数为空");
        }
        User loginUser = userService.getLoginUser(request);
        QueryWrapper<Orderaftersales> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("afterSalesId", orderaftersalesUpdate.getAfterSalesId());
        Orderaftersales orderaftersales = orderaftersalesService.getOne(queryWrapper);

        BeanUtils.copyProperties(orderaftersalesUpdate, orderaftersales);
        boolean result = orderaftersalesService.updateById(orderaftersales);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "更新订单售后失败");
        return ResultUtils.success(result);
    }

    /**
     * 审核订单售后（供应商负责人）
     *
     * @param orderaftersalesCheckRequest
     * @return
     */
    @PostMapping("/check")
    @ApiOperation(value = "审核订单售后（供应商负责人以及用户）")
    public BaseResponse<Boolean> checkOrderaftersalesById(@RequestBody OrderaftersalesCheckRequest orderaftersalesCheckRequest, HttpServletRequest request) {
        if (orderaftersalesCheckRequest.getAfterSalesId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数错误");
        }
        User loginUser = userService.getLoginUser(request);

        QueryWrapper<Orderaftersales> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("afterSalesId", orderaftersalesCheckRequest.getAfterSalesId());
        Orderaftersales one = orderaftersalesService.getOne(queryWrapper);
        ThrowUtils.throwIf(one == null, ErrorCode.NOT_FOUND_ERROR, "订单售后不存在");

        BeanUtils.copyProperties(orderaftersalesCheckRequest, one);
        one.setHandleTime(new Date());
        boolean result = orderaftersalesService.updateById(one);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "审核订单售后失败");
        return ResultUtils.success(result);
    }

    /**
     * 用户查询自己全部的订单售后
     *
     * @param orderaftersalesQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/get/all/user")
    @ApiOperation(value = "用户查询自己全部的订单售后")
    public BaseResponse<Page<OrderaftersalesVO>> getOrderaftersalesVOByUser(@RequestBody OrderaftersalesQueryRequest orderaftersalesQueryRequest, HttpServletRequest request) {
        long current = orderaftersalesQueryRequest.getCurrent() == 0 ? 1 : orderaftersalesQueryRequest.getCurrent();
        long size = orderaftersalesQueryRequest.getPageSize() == 0 ? 10 : orderaftersalesQueryRequest.getPageSize();

        Long userId = userService.getLoginUser(request).getId();
        //分页信息封装Page对象
        Page<OrderaftersalesVO> pageParam = new Page(current, size);
        Page<OrderaftersalesVO> queryWrapper = orderaftersalesService.getQueryWrapperByUser(pageParam, orderaftersalesQueryRequest, userId);
        return ResultUtils.success(queryWrapper);
    }

    /**
     * 负责人查询供应商全部的订单售后
     *
     * @param orderaftersalesQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/get/all/contact")
    @ApiOperation(value = "负责人查询供应商全部的订单售后（仅负责人）")
    public BaseResponse<Page<OrderaftersalesVO>> getOrderaftersalesVOByContact(@RequestBody OrderaftersalesQueryRequest orderaftersalesQueryRequest, HttpServletRequest request) {
        long current = orderaftersalesQueryRequest.getCurrent() == 0 ? 1 : orderaftersalesQueryRequest.getCurrent();
        long size = orderaftersalesQueryRequest.getPageSize() == 0 ? 10 : orderaftersalesQueryRequest.getPageSize();

        // 负责人id
        Long userId = userService.getLoginUser(request).getId();

        //分页信息封装Page对象
        Page<OrderaftersalesVO> pageParam = new Page(current, size);
        Page<OrderaftersalesVO> queryWrapper = orderaftersalesService.getQueryWrapperByContact(pageParam, orderaftersalesQueryRequest, userId);
        return ResultUtils.success(queryWrapper);
    }

    /**
     * 分页获取全部用户订单售后（仅管理员）
     *
     * @param orderaftersalesQueryRequest
     * @return
     */
    @PostMapping("/get/all")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @ApiOperation(value = "分页获取全部用户订单售后（仅管理员）")
    public BaseResponse<Page<OrderaftersalesVO>> listPurchaseOrdersByPage(@RequestBody OrderaftersalesQueryRequest orderaftersalesQueryRequest) {
        long current = orderaftersalesQueryRequest.getCurrent() == 0 ? 1 : orderaftersalesQueryRequest.getCurrent();
        long size = orderaftersalesQueryRequest.getPageSize() == 0 ? 10 : orderaftersalesQueryRequest.getPageSize();
        //分页信息封装Page对象
        Page<OrderaftersalesVO> pageParam = new Page(current, size);
        Page<OrderaftersalesVO> queryWrapper = orderaftersalesService.getQueryWrapperByAdmin(pageParam, orderaftersalesQueryRequest);
        return ResultUtils.success(queryWrapper);
    }
    // endregion

}
